package com.mk.api.sys;

import com.mk.base.model.response.Rsp;
import com.mk.model.request.ResourceRequest;
import com.mk.service.IResourceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @Author: yq
 * @Description:
 * @Date: Created in 3:18 PM 3/14/18
 */
@RestController
@RequestMapping("/resource")
public class ResourceApi {

    @Autowired
    private IResourceService resourceService;

    @RequestMapping(method = RequestMethod.POST)
    public Rsp saveResource(@RequestBody ResourceRequest request){
        try{
            return Rsp.SUCCESS(resourceService.save(request));
        }catch (Exception e){
            return Rsp.ERROR(e.getMessage());
        }
    }

    @RequestMapping(method = RequestMethod.PUT)
    public Rsp updateResource(@RequestBody ResourceRequest request){
        try{
            if(resourceService.update(request))
                return Rsp.SUCCESS("编辑资源信息成功");
            else
                return Rsp.ERROR("编辑资源信息失败");
        }catch (Exception e){
            return Rsp.ERROR(e.getMessage());
        }
    }

    @RequestMapping(value = "/{id}",method = RequestMethod.DELETE)
    public Rsp deleteResource(@PathVariable("id") Long id){
        try{
            if(resourceService.delete(id))
                return Rsp.SUCCESS("删除资源信息成功");
            else
                return Rsp.ERROR("删除资源信息失败");
        }catch (Exception e){
            return Rsp.ERROR(e.getMessage());
        }
    }

    @RequestMapping(value = "/{id}",method = RequestMethod.GET)
    public Rsp findById(@PathVariable("id") Long id){
        return Rsp.SUCCESS(resourceService.get(id));
    }

    @RequestMapping(method = RequestMethod.GET)
    public Rsp findAll(){
        return Rsp.SUCCESS(resourceService.getList());
    }

    @RequestMapping(value = "/role/{roleId}",method = RequestMethod.GET)
    public Rsp findByRoleId(@PathVariable("roleId") Long roleId){
        return Rsp.SUCCESS(resourceService.getResourcesByRoleId(roleId));
    }

    @RequestMapping(value = "/role/code",method = RequestMethod.GET)
    public Rsp findByRoleCode(@RequestParam("roleCode") String roleCode){
        return Rsp.SUCCESS(resourceService.getResourcesByRoleCode(roleCode));
    }

    @RequestMapping(value = "/type",method = RequestMethod.GET)
    public Rsp findByTypeAndParent(@RequestParam(value = "parentId",required = false) Long parentId,
                                   @RequestParam(value = "type",required = false) String type){
        return Rsp.SUCCESS(resourceService.getResources(parentId,type));
    }
}
